<template>
    <div class="num-box">
        <div
            :class="{'num-box-item':!isNaN(item),'mark-item':isNaN(item),'small':size=='small','middle':size=='middle'}"
            :key="index"
            v-for="(item,index) in renderNumber"
        >
            <i v-if="!isNaN(item)" ref="numberItem">0123456789</i>
            <span class="split" v-else>{{item}}</span>
        </div>
    </div>
</template>
<script>
function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
            return true;
        }
    }
    return false;
}
export default {
    name: "NumTransform",
    data() {
        return {
            renderNumber: [],
            newNumber: this.number,
        };
    },
    props: {
        size: {
            validator: function (value) {
                return oneOf(value, ["small", "middle", "default"]);
            },
            default: "default",
        },
        isAuto: {
            // 是否自动播放
            type: Boolean,
            default: false,
        },
        number: {
            //默认数字
            type: Number,
            default: 10,
        },
        splitLen: {
            // 分割长度
            type: Number,
            default: 3,
        },
    },
    computed: {},
    watch: {
        number(val) {
            this.formatNumber(val);
        },
        renderNumber(val) {
            if (!this.isAuto) {
                setTimeout(() => {
                    // 此处处理获取dom不及时导致数字渲染出错
                    this.setNumberTransform();
                }, 10);
            }
        },
    },
    mounted() {
        if (this.isAuto) {
            this.staticRender();
        } else {
            this.formatNumber(this.number);
        }
    },
    methods: {
        /**
         * 静态渲染师方法集合（使用async await 主要是为了处理获取dom不及时，导致数据滚动不对的问题）
         */
        async staticRender() {
            await this.formatNumber(this.number);
            await this.setNumberTransform();
            await this.changeNumber();
        },
        /**
         * 格式化数字
         */
        formatNumber(num) {
            let str = num.toString();
            let len = 2;
            let replaceStr = new RegExp(
                "([0-9]{" + this.splitLen + "})(?=[0-9])",
                "g"
            ); //`/(\d{3})(?=\d)/g`;
            const strArr = str
                .split("")
                .reverse()
                .join("")
                .replace(replaceStr, "$1,")
                .split("")
                .reverse();
            this.renderNumber = strArr; // num.padStart(8, "0").split("");
        },
        /**
         * 自动播放演示
         */
        changeNumber() {
            this.timer = setInterval(async () => {
                this.newNumber =
                    Number(this.newNumber) +
                    Number(this.getRandomNumber(1, 100));
                await this.formatNumber(this.newNumber);
                await this.setNumberTransform();
            }, 3000);
        },
        // 设置每一位数字的偏移
        setNumberTransform() {
            let numberItems = this.$refs.numberItem;
            let numberArr = this.renderNumber.filter((item) => !isNaN(item));
            for (let index = 0; index < numberItems.length; index++) {
                let elem = numberItems[index];
                elem.style.transform = `translate3d(-50%, -${
                    numberArr[index] * 10
                }%,0)`;
            }
        },
        /**
         * 设置随机数，返回数字
         */
        getRandomNumber(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        },
    },
    beforeDestroy() {
        clearInterval(this.timer);
    },
};
</script>
<style lang="less" scoped>
@import "./less/index.less";
</style>